package kroketwebspring.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import kroketwebspring.domain.Product;

public class SearchDAOImpl extends JdbcDaoSupport implements SearchDAO {

	@Override
	@SuppressWarnings("unchecked")
	public List<Product> searchProducts(String searchParam) {
		String query = "SELECT p.product_id AS product_id, p.product_name AS product_name, p.product_stock AS product_stock, q.price_value AS price_value"
			+ " FROM product p"
			+ " INNER JOIN price q"
			+ " ON p.product_id = q.product_id"
			+ " WHERE q.price_sDate < NOW()"
			+ " AND (q.price_eDate > NOW() OR q.price_eDate IS NULL)"
			+ " AND product_name LIKE '%"+searchParam+"%';";
		
		List<Product> productList = this.getJdbcTemplate().query(query, new ParameterizedRowMapper<Product>() {
			public Product mapRow(final ResultSet rs, final int rowNum) throws SQLException {
				Product output = new Product();
				output.setId(rs.getInt("product_id"));
				output.setName(rs.getString("product_name"));
				output.setStock(rs.getInt("product_stock"));
				output.setPrice(rs.getFloat("price_value"));
				return output;
			}
		});
		return productList;
		
	}

}
